package com.sgcc.pda.mdrh.task.safe.ui.ac;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.cepri.service.yingxiao.DtsManager;
import com.cepri.service.yingxiao.baidutts.BaiduTtsManager;
import com.cepri.service.yingxiao.baidutts.ITtsManager;
import com.sgcc.pda.baselibrary.utils.ToastUtils;
import com.sgcc.pda.mdrh.task.safe.R;
import com.sgcc.pda.mdrh.task.safe.entity.RiskBeforeResult;
import com.sgcc.pda.mdrh.task.safelibrary.BuildConfig;
import com.sgcc.pda.mdrh.utils.ToolGson2;
import com.sgcc.pda.mdrh.zoom.router.BaseOperateRouter;

/**
 * 描述：用于展示页面跳转认证提示
 * 作 者：小卷毛  2020-12-11 13:54
 * 修改描述：增加百度授权提示语
 * 修 改 人：
 * 修改版本：v1.2.1
 */
public class SafeTipDialogSecondActivity extends FragmentActivity {

    public static final String SAFE_VERITY_HINT = "safe_verity_hint";

    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;

    //倒计时
    TextView tvTime;
    //提示信息
    TextView tvMessage;
    //初始化语音合成
    ITtsManager ttsManager;

    private static BaseOperateRouter.CompleteListener completeListener;

    public static void setCompleteListener(BaseOperateRouter.CompleteListener listener) {
        completeListener = listener;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(R.style.SafeTipDialogTheme);
        setContentView(R.layout.activity_safe_tip_dialog_1);
        initView();

        // 判断百度语音初始化是否完成
        if (BuildConfig.USE_BAIDU_TTS) {
            if (!BaiduTtsManager.getInstance().isDone()) {
                ToastUtils.show(
                        this,
                        "语音未授权，请在个人中心进行授权申请！"
                );
            }
        }

        ttsManager.play(tvMessage.getText().toString());
    }

    private void initView() {
        //初始化语音合成
        if (BuildConfig.USE_BAIDU_TTS)
            ttsManager = BaiduTtsManager.getInstance();
        else ttsManager = DtsManager.getInstance();
        ttsManager.init(this);

        // ImageView动画
        ImageView ivProgress = findViewById(R.id.iv_progress);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.anim_rotate_repeat);
        animation.setInterpolator(new LinearInterpolator());
        ivProgress.startAnimation(animation);
        tvTime = findViewById(R.id.tv_time);
        //数据接收
        String message = getIntent().getStringExtra(SAFE_VERITY_HINT);
        tvMessage = findViewById(R.id.tv_msg);
        Button btnCancel = findViewById(R.id.btn_cancel);

        tvMessage.setText(message);
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ttsManager != null) {
                    ttsManager.stopSpeaking();
                }

                if (completeListener != null) {
                    RiskBeforeResult result = new RiskBeforeResult("1", "成功");
                    RiskBeforeResult.VerifyDetail verifyDetail =
                            new RiskBeforeResult.VerifyDetail(false, "未阅读作业前风险点！");
                    result.setDTS(verifyDetail);

                    completeListener.complete(1, ToolGson2.getJsonStr(result));
                }

                finish();
            }
        });
        // 点击确定打开页面或者关闭
        findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ttsManager != null) {
                    ttsManager.stopSpeaking();
                }

                openListActivity();
                finish();
            }
        });
        mTimer.start();
    }

    CountDownTimer mTimer = new CountDownTimer(10 * 1000, 1000) {
        public void onTick(long millisUntilFinished) {
            SpannableString spannableString = new SpannableString("倒计时 " + millisUntilFinished / 1000 + " 秒");
            spannableString.setSpan(
                    new ForegroundColorSpan(Color.RED),
                    spannableString.length() - 3,
                    spannableString.length() - 2,
                    Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            );
            tvTime.setText(spannableString);
        }

        public void onFinish() {
            openListActivity();
            finish();
        }
    };

    /**
     * 打开WebView
     */
    private void openListActivity() {
        //判断是否有读写权限
        if (!checkPermission()) return;
        if (completeListener != null)
            SafeMeasureActivity.setCompleteListener(completeListener);

        Intent intent = getIntent();
        intent.setClass(this, SafeMeasureActivity.class);
        startActivity(intent);
    }

    /**
     * 判断是否有文件读写权限
     */
    private boolean checkPermission() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
                ToastUtils.show(this, "请先开启文件读写权限");
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permissions[i])) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        openListActivity();
                    }
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
        }
    }

}
